# -*- coding: utf-8 -*-

import os
import sys
import urlparse
import urllib
import locale
import threading
import time
import subprocess
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
import urllib2
import json
import datetime

__addon_id__ = 'plugin.browser.undermedia'
__addon__ = xbmcaddon.Addon(id=__addon_id__)
__addonversion__ = __addon__.getAddonInfo('version')
__addonname__ = __addon__.getAddonInfo('name')
__localize__ = __addon__.getLocalizedString

libraries = os.path.join(__addon__.getAddonInfo('Path') , 'lib')
sys.path.append (libraries)

import undermedia



from undermedia import api
from xbmcswift2 import Plugin, ListItem

plugin = Plugin(__addonname__, __addon_id__, __file__, 'video')

if (not __addon__.getSetting("firstrun")):
    __addon__.openSettings();
    __addon__.setSetting("firstrun", "1")


__undermedia_username__ = __addon__.getSetting("username")
__undermedia_password__ = __addon__.getSetting("password")
__undermedia_ask_for_trailers__ = __addon__.getSetting("ask_for_trailers")

UndermediaApi = api.Api(__undermedia_username__, __undermedia_password__)

@plugin.route('/')
def index():
    result = UndermediaApi.get_categories()
    items = [{
        'label': item['label'],
        'path': 'plugin://%s/category/%s' % (__addon_id__, item['kreq']),
        'thumbnail': item['thumbnail']
    } for item in result]
    return items

@plugin.route('/search')
def main_search():
    search_string = plugin.keyboard(heading=_('search'))
    if search_string:
        plugin.log.info("Search: " + search_string)

@plugin.route('/category/<kreq>')
def get_category(kreq):
    result = UndermediaApi.get_category_content(kreq)
    items = [{
        'label': item['label'],
        'path': 'plugin://%s/item/%s' % (__addon_id__, item['kreq']),
        'thumbnail': item['thumbnail']
    } for item in result]
    
    return items

@plugin.route('/item/<kreq>')
def get_item(kreq):
    result = UndermediaApi.get_item_content(kreq)
    items = [{
        'label': item['label'],
        'info_type' : item['info_type'],
        'info': { 
                 'title': item['label'],
                 'plot':  item['plot'],
                 'duration': item['duration'],
                 'size': item['size'],
                 'tagline' : 'tagline'
                 },
        'properties': item['properties'],
        'path': 'plugin://%s/%s/%s' % (__addon_id__, item['play_type'], item['kreq']),
        'thumbnail': item['thumbnail'],
        'is_playable': True
    } for item in result]
    finish_kwargs = {
        'sort_methods': ('TITLE', 'DATE', 'SIZE'),
        'view_mode' : 'thumbnail'
    }
    return plugin.finish(items, **finish_kwargs)

@plugin.route('/search/category/<kreq>')
def category_search(kreq):
    search_string = plugin.keyboard(heading=_('search'))
    if search_string:
        plugin.log.info("Search: " + search_string)

@plugin.route('/stream/<kreq>')
def get_stream(kreq):
    result = UndermediaApi.get_stream_content(kreq)
    print result
    '''
    ['title'] => 'Salmon Fishing in the Yemen'
    ['thumbnail'] => 'https://d3gtl9l2a4fn1j.cloudfront.net/t/p/w500/uIOZfLy5c67Oc1kA2aaQ5jhF8Cx.jpg'
    ['video_url'] => 'http://mist001.is-by.us/47745642-3982-4101-a79e-a1b2862844b6.m3u8'
    ['trailer_url'] => 'plugin://plugin.video.youtube/?path=/root&action=play_video&videoid=UyZMPit4UtM'
    ['subtitles'] =>
        ['es'] => 'https://api.undermedia.is-by.us:443/storage?k=aXloSkpnZnZuSFVGV0JpblBzNmlTMlF0VlBRNnpDcW5ZTVZRdDBlSVJHVWtKQ3hsZXlnSlNQWEJuQzF0Z19FQUVCazY2UU5wSllpOVRYbkVIR2kwTlVNYlJhd3EyMTQycU54Qm1Pb2JCaU5mTEkzZ3JmTmhKcEUzZXZYVi1xV01IYXZZalZzY0JqRUk4ZDhQbW9wZm13Mm1uWm1XUDkxZkZUcm5pRHFNdGs4VHU1eDNaSUw4YzYwdHRuZlBubU5jeGJLbEhWX2paU3lUZEtvblc4YlZvVlBTdWIzSTN2bmxHaWpKR1JIeDg5ODlBeUhXRW9FdV83dld0YzFwelctdFVNUnRWLXpkYmo0dXRpemdrTjZWUWxoVXp5clQwWmRTS1Z1N1c2VkpROUF0UHJqYzM3bWpxa1NLMWhNa2NRRDRmN3BRanNYbVI1bWJaR2JQX09qdklPblNxeFZFYnRxMm95a3gyR0s5YnVSN2h0Z3J3cGk3QmlrUVRKVm5SWDl2Rlc1TDlCVlZXRlVWRklpeG1NbFZqTzRkV2xaczZxbFpSSFA4dGdmTmdqLXRhVThwTEJrSUdKc1lsci1ZdVhaMHY1ajMxNkM2M3JQZnFWR3k1dTdGWTJ5cA=='
    '''
    plugin.log.info(result['video_url'])
    if result['video_url'].startswith("rtmp://"):
        result['video_url'] = result['video_url'] + " swfUrl=" + result['param_swfurl'] + " live=false pageUrl=" + result['video_url']
    '''
    |User-Agent=%s
    '''
    play_movie = True
    if __undermedia_ask_for_trailers__ == True and result['trailer_url'] != '':
        trailer_ok = xbmcgui.Dialog().yesno("Do you want to see the trailer first?", "You can modify this behavior in Add-on settings", "")
        if trailer_ok == 1:
            play_movie = False
            result['video_url'] = result['trailer_url']
            plugin.log.info('video_url replaced with trailer: %s' % result['video_url'])
    
    choice_subtitle = False
    if play_movie == True and result.get('subtitles'):
        lang_dict = {'none': 'None', 'en': 'English', 'es': 'Spanish'}
        lang_dict_inversed = { 'None' : False, 'English' : 'en', 'Spanish' : 'es'}
        lang_codes = []
        lang_codes_inv = []
        lang_codes.append(lang_dict['none'])
        lang_codes_inv.append(lang_dict_inversed[lang_dict['none']])
        
        for idx in result['subtitles']:
            lang_codes.append(lang_dict[idx])
            lang_codes_inv.append(lang_dict_inversed[lang_dict[idx]])
        choice_subtitle = xbmcgui.Dialog().select('Select Subtitle Language' , lang_codes)
    plugin.log.info('Playing url: %s' % result['video_url'])
    listitem = ListItem(label=result['title'], icon=result['thumbnail'], thumbnail=result['thumbnail'], path=result['video_url'])
    # listitem.set_property("IsLive", "false")
    plugin.set_resolved_url(listitem)
    if choice_subtitle != False:
        plugin.log.info('Selected Language for Subtitles : %s' % lang_codes_inv[choice_subtitle])
        plugin.log.info('Selected Url for Subtitles : %s' % result['subtitles'][lang_codes_inv[choice_subtitle]])
        player = xbmc.Player()
        i = 0
        while not player.isPlaying():
            i += 1
            plugin.log.info("Waiting for playback to start ")
            time.sleep(1)
            if i > 10:
                break
        plugin.log.info("Setting subtitle file %s" % result['subtitles'][lang_codes_inv[choice_subtitle]])
        xbmc.Player().setSubtitles(result['subtitles'][lang_codes_inv[choice_subtitle]])

if __name__ == '__main__':
    plugin.run()
